package com.eqdd.yiqidian.ui.gongneng.kehu;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.arlib.floatingsearchview.FloatingSearchView;
import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion;
import com.eqdd.yiqidian.KehuActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.ClientListResultBean;
import com.eqdd.yiqidian.bean.rebuild.ZhangPageResultBean;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.utils.DateUtil;
import com.eqdd.yiqidian.utils.SwipeUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import org.reactivestreams.Publisher;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

public class KehuActivity extends BaseActivity {
    private KehuActivityCustom dataBinding;
    private SlimAdapterEx<ClientListResultBean> slimAdapterEx;
    private MVCCoolHelper<List<ClientListResultBean>> mvcHelper;
    private ModelRx2DataSource<ClientListResultBean> dataSource;
    private int pageNum = 0;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_kehu);
        initTopTitleBar(View.VISIBLE, "客户列表");
        initTopRightText("添加", v -> {

            startActivityForResult(AddKehuActivity.class, null, Config.ADD_KEHU);
        });
    }

    @Override
    public void initData() {
        if (slimAdapterEx == null) {
            SwipeUtil.openSwipe(this, dataBinding.recyclerView, (menuBridge, pos) -> {
                OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.DELETE_KEHU)
                        .params("owner", user.getGuid())
                        .params("cusid", slimAdapterEx.getDataItem(pos).getId())
                        .execute(new DialogCallBack<HttpResult>(KehuActivity.this) {
                            @Override
                            public void onSuccess(Response<HttpResult> response) {
                                HttpResult httpResult = response.body();
                                ToastUtil.showShort(httpResult.getMsg());
                                if (httpResult.getStatus() == 200) {
                                    menuBridge.closeMenu();
                                    slimAdapterEx.getData().remove(pos);
                                    slimAdapterEx.notifyItemRemoved(pos);
                                }
                            }
                        });
            });
            dataBinding.recyclerView.setSwipeItemClickListener((itemView, position) -> {
                Bundle bundle = new Bundle();
                bundle.putSerializable(Config.KEHU_BEAN, slimAdapterEx.getDataItem(position));
                bundle.putString("cosid", slimAdapterEx.getDataItem(position).getId() + "");
                startActivity(UpdateKehuActivity.class, bundle);
            });
            dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
            slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_12, new SlimInjector<ClientListResultBean>() {
                @Override
                public void onInject(ClientListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_upper_left_content, data.getCusName())
                            .text(R.id.tv_upper_right_content, data.getCusCall() + "")
                            .text(R.id.tv_down_left_content, data.getCusType())
                            .text(R.id.tv_down_right_content, data.getSalesTerritory());
                }
            }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
            dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
                @Override
                public Flowable<List> loadSourcce(int page, Rx2DataSource.DoneActionRegister register) {
                    return OkGo.<ZhangPageResultBean<List<ClientListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.KEHU_LIST)
                            .params("page", pageNum)
                            .params("owner", user.getGuid())
                            .converter(new JsonConverter<ZhangPageResultBean<List<ClientListResultBean>>>() {
                                @Override
                                public void test() {
                                    super.test();
                                }
                            }).adapt(new FlowableBody<ZhangPageResultBean<List<ClientListResultBean>>>())
                            .flatMap(new Function<ZhangPageResultBean<List<ClientListResultBean>>, Publisher<List<ClientListResultBean>>>() {
                                @Override
                                public Publisher<List<ClientListResultBean>> apply(@NonNull ZhangPageResultBean<List<ClientListResultBean>> noticeWraperResultBeanHttpResult) throws Exception {
                                    if (page == 1) {
                                        mvcHelper.setAutoLoadMore(true);
                                    }
                                    pageNum = page == 1 ? 0 : noticeWraperResultBeanHttpResult.getNextpage();
                                    return Flowable.just(noticeWraperResultBeanHttpResult.getItems() == null ? new ArrayList() : noticeWraperResultBeanHttpResult.getItems());
                                }
                            });
                }
            }, 10);
            mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
            mvcHelper.setDataSource(dataSource);
            mvcHelper.setAdapter(slimAdapterEx);
            mvcHelper.refresh();
            dataBinding.floatingSearchView.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
                @Override
                public void onSuggestionClicked(SearchSuggestion searchSuggestion) {

                }

                @Override
                public void onSearchAction(String currentQuery) {
                    mvcHelper.setAutoLoadMore(false);

                    OkGo.<HttpResult<List<ClientListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.KEHU_SEARCH)
                            .params("param", currentQuery)
                            .execute(new DialogCallBack<HttpResult<List<ClientListResultBean>>>(KehuActivity.this) {
                                @Override
                                public void onSuccess(Response<HttpResult<List<ClientListResultBean>>> response) {
                                    HttpResult<List<ClientListResultBean>> httpResult = response.body();
                                    ToastUtil.showShort(httpResult.getMsg());
                                    if (httpResult.getStatus() == 200) {
                                        slimAdapterEx.updateData(httpResult.getItems());
                                    }
                                }
                            });
                }
            });
//            dataBinding.coolRefreshView.addOnPullListener(new OnPullListener() {
//                @Override
//                public void onPullBegin(CoolRefreshView refreshView) {
//
//                }
//
//                @Override
//                public void onPositionChange(CoolRefreshView refreshView, int status, int dy, int currentDistance) {
//
//                }
//
//                @Override
//                public void onRefreshing(CoolRefreshView refreshView) {
//
//                    refresh();
//                }
//
//                @Override
//                public void onReset(CoolRefreshView refreshView, boolean pullRelease) {
//
//                }
//
//                @Override
//                public void onPullRefreshComplete(CoolRefreshView refreshView) {
//
//                }
//            });
//            dataBinding.coolRefreshView.setRefreshing(true);
        }
    }

//    private void refresh() {
//        OkGo.<HttpResult<List<ClientListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.KEHU_LIST)
//                .params("owner", user.getGuid())
//                .params("page", 0)
//                .execute(new JsonCallBack<HttpResult<List<ClientListResultBean>>>() {
//                    @Override
//                    public void onSuccess(Response<HttpResult<List<ClientListResultBean>>> response) {
//                        HttpResult<List<ClientListResultBean>> httpResult = response.body();
//                        ToastUtil.showShort(httpResult.getMsg());
//                        if (httpResult.getStatus() == 200) {
//                            slimAdapterEx.updateData(httpResult.getItems());
//                            dataBinding.coolRefreshView.setRefreshing(false);
//                        }
//                    }
//                });
//    }

    @Override
    public void setView() {


    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            mvcHelper.refresh();
        }
    }
}
